package com.junzhiit.nengji.api.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.junzhiit.nengji.api.service.AreaService;
import com.junzhiit.nengji.api.web.util.Constants;
import com.junzhiit.nengji.api.web.vo.AreaTreeVO;
import com.junzhiit.nengji.api.web.vo.AreaVO;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.dao.AreaDAO;
import com.junzhiit.nengji.model.Area;

@Service
public class AreaServiceImpl extends BaseServiceImpl implements AreaService {

	@Autowired
	private AreaDAO areaDAO;
	
	@Override
	public ResultVO findInfo(AreaVO areaVO){
		ResultVO result=new ResultVO();
		Area area=new Area();
		BeanUtils.copyProperties(areaVO, area);
		List<Area> data=areaDAO.findInfo(area);
		result.setData(data);
		return result;
	}
	
	@Override
	public ResultVO findAll(){
		ResultVO result=new ResultVO();
		
		List<Area> dataList=areaDAO.findAll();
	    
		AreaTreeVO root=tree(dataList);
		
		result.setData(root);
		
		return result;
	}
	
	
	private AreaTreeVO tree(List<Area> dataList){
		// 节点列表（散列表，用于临时存储节点对象）  
		HashMap<Integer, AreaTreeVO> nodeList = new HashMap<Integer, AreaTreeVO>();  
		// 根节点  
		AreaTreeVO root = new AreaTreeVO();
		root.setLabel(Constants.ROOT_VALUE);
		root.setChildren(new ArrayList<AreaTreeVO>());


		// 根据结果集构造节点列表（存入散列表）  
		for (Area area : dataList) { 
			AreaTreeVO node = new AreaTreeVO();
			BeanUtils.copyProperties(area, node);
			node.setLabel(area.getName());
			node.setChildren(new ArrayList<AreaTreeVO>());
			nodeList.put(node.getCityId(), node);  
		}

		// 构造无序的多叉树
		Set<Entry<Integer, AreaTreeVO>> entrySet = nodeList.entrySet();  
		for (Iterator<Entry<Integer, AreaTreeVO>> it = entrySet.iterator(); it.hasNext();) {  
			AreaTreeVO areaTreeVO= it.next().getValue();

			if(areaTreeVO.getParentId() == null || Constants.ZERO == areaTreeVO.getParentId().intValue()){
				root.getChildren().add(areaTreeVO);
			}else{
				nodeList.get(areaTreeVO.getParentId()).getChildren().add(areaTreeVO); 
			}

		}
		
		// 对多叉树进行横向排序
		root.sortChildren();


		return root;
	}

}
